package com.dream.airinfo;

import android.util.Log;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by on 2017/7/25.
 */

public class GetHttpData {

    private Document doc;
    private int count=0;
    private String[] citys;
    private List<String[]> cityInfoList,cityRankList;
    private Elements city_name,update_time;
    private Elements elementsValue;

    public GetHttpData(String[] citys) {
        this.citys = citys;
        cityInfoList=new ArrayList<>();
    }

    public void getResult(OnFinshData onFinshData){
        for (int i = 0; i < citys.length; i++) {
            getData(citys[i],onFinshData);
        }
    }

    //循环请求数据源，请求完成请用接口回调数据
    private void getData(final String city, final OnFinshData onFinshData){
                try {
                    //抓取当前网站 city_name 和 value 返回List集合
                    doc= Jsoup.connect("http://www.pm25.in/"+city).get();
                    city_name = doc.getElementsByAttributeValue("class", "city_name");
                    elementsValue = doc.getElementsByAttributeValue("class", "value");
                    String[] str=new String[elementsValue.size()];
                    str[0]=city_name.get(0).text();
                    for (int i = 0; i < elementsValue.size()-1; i++) {
                        str[i+1]=elementsValue.get(i).text();
                    }
                    cityInfoList.add(str);
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    setCount(onFinshData);
                }
    }


    private void setCount(OnFinshData onFinshData){
        count++;
        if (count==citys.length){
            onFinshData.success(cityInfoList);
        }
    }

    public interface OnFinshData{
        void success(List<String[]> cityInfoList);
    }

}
